<?php
/**
 * +-------------------------------------------------------------
 * |Caption:
 * +-------------------------------------------------------------
 * |Author: Lenny
 * +-------------------------------------------------------------
 * |Email:  1685964109@qq.com
 * +-------------------------------------------------------------
 * |Date:   2024/6/20 上午10:28
 * +-------------------------------------------------------------
 */

namespace app\admin\controller;

use app\admin\model\SysMenu;
use app\admin\validate\SysMenuValidate;
use app\common\constants\MenuConstant;
use app\common\controller\AdminController;
use app\common\service\MenuService;
use app\Request;
use think\App;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use think\facade\Db;
use think\response\Json;
use app\admin\service\annotation\ControllerAnnotation;
use app\admin\service\annotation\NodeAnnotation;

/**
 * @ControllerAnnotation (title="菜单管理")
 */
class Menu extends AdminController
{
    public function __construct(App $app)
    {
        parent::__construct($app);
        $this->model         = new SysMenu();
        $this->validateClass = SysMenuValidate::class;
        $this->sort          = ['sort' => 'desc', 'id'   => 'asc'];
    }

    /**
     * @NodeAnnotation (title="菜单列表")
     * @return Json
     */
    public function list(): Json
    {
        //菜单服务类
        $menuService = new MenuService($this->adminUid);
        $menuList = $menuService->getMenuTree();
        return $this->successJson($menuList);
    }


    /**
     * @NodeAnnotation (title="新增")
     * @param Request $request
     * @return Json
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function add(Request $request): Json
    {
        if(!$request->isPost()) return $this->errorJson('当前请求不合法！');
        $pid = $request->post('pid', 0);
        if($pid){
            $pMenu = $this->model->getPidMenu($pid);
            if(!$pMenu) return $this->errorJson('父级菜单不存在！');
            if($pMenu->type == MenuConstant::BUTTON_TYPE) return $this->errorJson('父级菜单为按钮，无法新增子菜单！');
        }
        $param = $request->post();
        if(!$this->sceneValidate($param, 'add')) return $this->errorJson($this->msg);
        try {
            Db::transaction(function () use ($param, &$save)
            {
                $save = $this->model->save($param);
            });
        } catch(\Exception $e) {
            return $this->errorJson('新增失败:' . $e->getMessage());
        }
        if(!$save) return $this->errorJson('新增失败');
        return $this->successJson('新增成功');
    }
}